<template>
	<view class="login-page">
		<!-- Logo区域 -->
		<view class="logo-section">
			<view class="logo-container">
				<image src="/static/images/logo.png" class="logo-image" mode="aspectFit" />
			</view>
			<text class="app-title">链智Quant AI</text>
		</view>

		<!-- 登录方式切换 -->
		<view class="login-switch">
			<text class="switch-text" :class="{ active: loginType === 2 }" @click="switchLoginType(2)">邮箱登录</text>
			<text class="switch-divider">|</text>
			<text class="switch-text" :class="{ active: loginType === 0 }" @click="switchLoginType(0)">账号登录</text>
		</view>

		<!-- 表单区域 -->
		<view class="form-section">
			<!-- 用户名输入 -->
			<view class="input-group">
				<view class="input-container">
					<image src="/static/images/login/phone.png" class="input-icon" />
					<input v-model="formData.username" class="input-field" placeholder="请输入邮箱地址" />
				</view>
			</view>

			<!-- 邮箱验证码登录 -->
			<template v-if="loginType === 2">
				<!-- 验证码输入 -->
				<view class="input-group">
					<view class="input-container">
						<image src="/static/images/login/safety.png" class="input-icon" />
						<input v-model="formData.captcha" class="input-field" placeholder="请输入邮箱验证码" maxlength="6" />
						<view class="sms-btn" @click="sendEmailCode" :class="{ disabled: isSending || countdown > 0 }">
							<text class="sms-btn-text">{{ countdown > 0 ? `${countdown}s后重发` : '获取验证码' }}</text>
						</view>
					</view>
				</view>
			</template>

			<!-- 密码登录 -->
			<template v-if="loginType === 0">
				<!-- 密码输入 -->
				<view class="input-group">
					<view class="input-container">
						<image src="/static/images/login/lock.png" class="input-icon" />
						<input v-model="formData.password" class="input-field" placeholder="请输入密码" :password="true" />
					</view>
				</view>
			</template>

			<!-- 协议勾选 -->
			<view class="agreement-section">
				<view class="checkbox-container" @click="toggleAgreement">
					<view class="checkbox" :class="{ checked: isAgreed }">
						<text v-if="isAgreed" class="check-icon">✓</text>
					</view>
					<text class="agreement-text">我已阅读并同意</text>
					<text class="link-text" @click.stop="goToUserManual">《用户手册》</text>
					<text class="agreement-text">和</text>
					<text class="link-text" @click.stop="goToPrivacyPolicy">《隐私政策》</text>
				</view>
			</view>

			<!-- 登录按钮 -->
			<view class="login-btn" :class="{ disabled: !canLogin }" @click="handleLogin">
				<text class="login-btn-text">登录</text>
			</view>

			<!-- 底部链接 -->
			<view class="bottom-links">
				<view class="link-item">
					<text class="link-prefix">没有账户？</text>
					<text class="link-text primary" @click="goToRegister">立即注册</text>
				</view>
				<view class="link-item">
					<text class="link-text" @click="goToForgetPassword">忘记密码？</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import {
	mapActions
} from 'vuex'
import {
	getEmailCaptcha
} from '@/api/auth'
import { checkCaptchaThrottle } from '@/utils/captcha-throttle'

export default {
	name: 'Login',
	data() {
		return {
			showFirst: true,
			loading: false,
			loginType: 2, // 登录类型：0-密码登录，2-邮箱验证码登录
			formData: {
				username: '',
				password: '',
				captcha: '',
			},
			clientId: '',
			checkboxValue: [],
			rememberValue: [],
			isAgreed: false,
			countdown: 0, // 倒计时秒数
			isSending: false, // 是否正在发送验证码
			timer: null, // 倒计时定时器
			lastClickTime: 0, // 上次点击时间，用于防抖
		}
	},

	computed: {
		canLogin() {
			// 根据登录类型判断是否可以登录
			if (this.loginType === 2) {
				// 邮箱验证码登录
				return (
					this.formData.username &&
					this.formData.captcha &&
					this.isAgreed &&
					!this.loading
				)
			} else {
				// 密码登录
				return (
					this.formData.username &&
					this.formData.password &&
					this.isAgreed &&
					!this.loading
				)
			}
		},
	},

	mounted() {
		this.loadSavedData()
		uni.getPushClientId({
			success: (res) => {
				console.log('获取Push客户端ID成功:', res);
				this.clientId = res.cid
				console.log('clientId:', this.clientId);
			},
			fail(err) {
				console.error('获取Push客户端ID失败:', err)
				// 获取失败时使用设备唯一标识作为备选
				try {
					const systemInfo = uni.getSystemInfoSync()
					this.clientId = systemInfo.deviceId || systemInfo.system || 'unknown'
				} catch (e) {
					this.clientId = 'fallback_' + Date.now()
				}
			}
		})
	},

	beforeDestroy() {
		// 清理定时器
		if (this.timer) {
			clearInterval(this.timer)
		}
	},

	methods: {
		...mapActions('user', ['login']),

		// 切换登录方式
		switchLoginType(type) {
			this.loginType = type
			// 清空不需要的字段
			if (type === 2) {
				this.formData.password = ''
			} else {
				this.formData.captcha = ''
			}
		},

		// 切换协议同意状态
		toggleAgreement() {
			this.isAgreed = !this.isAgreed
		},

		// 发送邮箱验证码
		sendEmailCode() {
			// 判断是否可以发送
			if (this.isSending || this.countdown > 0) return

			// 验证邮箱
			if (!this.formData.username) {
				uni.showToast({
					title: '请输入邮箱地址',
					icon: 'none',
				})
				return
			}

			// 验证邮箱格式
			const emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
			if (!emailReg.test(this.formData.username)) {
				uni.showToast({
					title: '请输入正确的邮箱地址',
					icon: 'none',
				})
				return
			}

			// 防抖检查：1秒内最多4个请求
			const throttleCheck = checkCaptchaThrottle()
			if (!throttleCheck.canSend) {
				uni.showToast({
					title: throttleCheck.message,
					icon: 'none',
				})
				return
			}

			this.isSending = true

			// 调用发送邮箱验证码接口
			getEmailCaptcha(this.formData.username)
				.then(response => {
					this.isSending = false
					if (response.code === 200) {
						uni.showToast({
							title: '验证码已发送',
							icon: 'none',
						})
						// 开始倒计时
						this.startCountdown()
					} else {
						uni.showToast({
							title: response.message || '发送失败',
							icon: 'none',
						})
					}
				})
				.catch(error => {
					this.isSending = false
					uni.showToast({
						title: error.message || '发送失败',
						icon: 'none',
					})
				})
		},

		// 开始倒计时
		startCountdown() {
			this.countdown = 60
			this.timer = setInterval(() => {
				this.countdown--
				if (this.countdown <= 0) {
					clearInterval(this.timer)
					this.timer = null
				}
			}, 1000)
		},

		loadSavedData() {
			try {
				const isShowFirst = uni.getStorageSync('isShowFirst')
				const isCheckedRemember = uni.getStorageSync('isCheckedRemember')
				const userInfo = uni.getStorageSync('userInfo')

				this.showFirst = !isShowFirst

				if (isCheckedRemember && !this.showFirst && userInfo) {
					this.formData.username = userInfo.username || ''
					this.formData.password = userInfo.password || ''
					this.rememberValue = ['remember']
				}
			} catch (e) {
				console.error('加载保存数据失败：', e)
			}
		},

		// 处理登录
		handleLogin() {
			if (!this.canLogin) return

			// 防抖检查：500ms内不允许重复点击
			const now = Date.now()
			if (now - this.lastClickTime < 500) {
				return
			}
			this.lastClickTime = now

			// 验证邮箱
			if (!this.formData.username) {
				uni.showToast({
					title: '请输入邮箱地址',
					icon: 'none',
				})
				return
			}

			// 根据登录类型验证
			if (this.loginType === 2) {
				// 邮箱验证码登录 - 验证验证码
				if (!this.formData.captcha) {
					uni.showToast({
						title: '请输入验证码',
						icon: 'none',
					})
					return
				}
			} else {
				// 密码登录 - 验证密码
				if (!this.formData.password || this.formData.password.length < 8) {
					uni.showToast({
						title: '密码至少8位',
						icon: 'none',
					})
					return
				}
			}

			this.loading = true

			// 确保clientId存在
			if (!this.clientId) {
				console.warn('clientId未获取到，使用临时ID')
				this.clientId = 'temp_' + Date.now()
			}

			// 构建登录参数 - 根据登录类型传递对应参数
			const loginData = {
				username: this.formData.username,
				loginType: this.loginType,
				uniClientId: this.clientId
			}

			// 根据登录类型添加对应参数
			if (this.loginType === 2) {
				// 邮箱验证码登录 - 只传 captcha
				loginData.captcha = this.formData.captcha
			} else {
				// 密码登录 - 只传 password
				loginData.password = this.formData.password
			}

			console.log('登录参数:', loginData)
			console.log('登录类型:', this.loginType === 2 ? '邮箱验证码登录' : '密码登录')

			this.login(loginData)
				.then(response => {
					console.log(response, 'response')
					this.loading = false
					uni.switchTab({
						url: '/pages/index/index'
					})
				})
				.catch(e => {
					this.loading = false
					// 清空验证码
					this.formData.captcha = ''
					console.error('登录失败：', e)
					uni.showToast({
						title: e.message || '登录失败',
						icon: 'none',
					})
				})
		},

		// 跳转到用户手册
		goToUserManual() {
			uni.navigateTo({
				url: '/subPages/auth/user-manual'
			})
		},

		// 跳转到隐私政策
		goToPrivacyPolicy() {
			uni.navigateTo({
				url: '/subPages/auth/privacy'
			})
		},

		// 跳转到注册页面
		goToRegister() {
			uni.navigateTo({
				url: '/subPages/auth/register'
			})
		},

		// 跳转到忘记密码页面
		goToForgetPassword() {
			uni.navigateTo({
				url: '/subPages/auth/forget'
			})
		},
	},
}
</script>
<style lang="scss" scoped>
.login-page {
	display: flex;
	flex-direction: column;
	align-items: center;
	min-height: 100vh;
	padding: 0;
	background: url('/static/images/login/login-bg.png') no-repeat center center;
	background-size: cover;
}

// Logo区域
.logo-section {
	margin-top: 160rpx;
	margin-bottom: 60rpx;
	text-align: center;

	.logo-container {
		margin-bottom: 40rpx;

		.logo-image {
			width: 160rpx;
			height: 160rpx;
			border-radius: 32rpx;
			box-shadow: 0 10rpx 40rpx rgba(0, 212, 170, 0.2);
		}
	}

	.app-title {
		font-size: 48rpx;
		font-weight: 600;
		color: #333;
		letter-spacing: 2rpx;
	}
}

// 登录方式切换 - 极简文字切换
.login-switch {
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 30rpx;
	margin: 0 60rpx 60rpx;

	.switch-text {
		font-size: 32rpx;
		color: #c0c4cc;
		font-weight: 500;
		transition: all 0.25s ease;
		position: relative;

		&.active {
			color: #00d4aa;
			font-weight: 600;

			// &::after {
			// 	content: '';
			// 	position: absolute;
			// 	bottom: -8rpx;  
			// 	left: 0;
			// 	right: 0;
			// 	height: 3rpx;
			// 	background: #00d4aa;
			// 	border-radius: 2rpx;
			// 	animation: fadeIn 0.3s ease;
			// }
		}

		&:active {
			opacity: 0.7;
		}
	}

	.switch-divider {
		font-size: 32rpx;
		color: #e4e7ed;
		user-select: none;
	}
}

@keyframes fadeIn {
	from {
		opacity: 0;
		transform: scaleX(0);
	}

	to {
		opacity: 1;
		transform: scaleX(1);
	}
}

// 表单区域
.form-section {
	flex: 1;
	width: 100%;
	padding: 0 60rpx;
}

// 输入框组
.input-group {
	margin-bottom: 40rpx;

	.input-container {
		position: relative;
		display: flex;
		align-items: center;
		height: 100rpx;
		padding: 0 30rpx;
		background-color: #fff;
		border: 2rpx solid transparent;
		border-radius: 50rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
		transition: all 0.3s ease;

		&:focus-within {
			border-color: #00d4aa;
			box-shadow: 0 4rpx 20rpx rgba(0, 212, 170, 0.15);
		}

		.input-icon {
			width: 32rpx;
			height: 40rpx;
			margin-right: 20rpx;
			opacity: 0.6;
		}

		.input-field {
			flex: 1;
			height: 100%;
			font-size: 32rpx;
			color: #333;
			background: transparent;
			border: none;
			outline: none;

			&::placeholder {
				font-size: 30rpx;
				color: #b0b8c1;
			}
		}

		.sms-btn {
			display: flex;
			align-items: center;
			justify-content: center;
			min-width: 180rpx;
			height: 60rpx;
			padding: 0 20rpx;
			margin-left: 20rpx;
			cursor: pointer;
			transition: all 0.3s ease;

			&:active {
				opacity: 0.7;
			}

			&.disabled {
				cursor: not-allowed;
			}

			.sms-btn-text {
				font-size: 26rpx;
				font-weight: 500;
				color: #00c299;
				white-space: nowrap;
			}

			&.disabled .sms-btn-text {
				color: #999;
			}
		}
	}
}

// 协议区域
.agreement-section {
	margin-bottom: 60rpx;

	.checkbox-container {
		display: flex;
		flex-wrap: nowrap;
		align-items: center;

		.checkbox {
			display: flex;
			align-items: center;
			justify-content: center;
			width: 32rpx;
			height: 32rpx;
			margin-right: 16rpx;
			background-color: #fff;
			border: 2rpx solid #00d4aa;
			border-radius: 6rpx;
			transition: all 0.3s ease;

			&.checked {
				background: linear-gradient(135deg, #00d4aa, #00c299);
				border-color: #00c299;
			}

			.check-icon {
				font-size: 20rpx;
				font-weight: bold;
				color: #fff;
			}
		}

		.agreement-text {
			margin-right: 4rpx;
			font-size: 26rpx;
			color: #666;
		}

		.link-text {
			margin-right: 4rpx;
			font-size: 26rpx;
			color: #00d4aa;
			text-decoration: underline;
		}
	}
}

// 登录按钮
.login-btn {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 100%;
	height: 100rpx;
	margin-bottom: 20rpx;
	background: linear-gradient(135deg, #00d4aa, #00c299);
	border-radius: 50rpx;
	box-shadow: 0 10rpx 30rpx rgba(0, 212, 170, 0.35);
	transition: all 0.3s ease;

	&:active:not(.disabled) {
		transform: scale(0.98);
		box-shadow: 0 6rpx 20rpx rgba(0, 212, 170, 0.35);
	}

	&.disabled {
		background: #e0e5eb;
		box-shadow: none;

		.login-btn-text {
			color: #999;
		}
	}

	.login-btn-text {
		font-size: 36rpx;
		font-weight: 600;
		color: #fff;
		letter-spacing: 2rpx;
	}
}

// 底部链接
.bottom-links {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 16rpx;
	margin-bottom: 20rpx;

	.link-item {
		display: flex;
		align-items: center;
		justify-content: center;

		.link-prefix {
			font-size: 28rpx;
			color: #8892a0;
			margin-right: 8rpx;
		}

		.link-text {
			font-size: 28rpx;
			color: #666;
			transition: color 0.3s ease;

			&.primary {
				color: #00d4aa;
				font-weight: 500;
			}

			&:active {
				opacity: 0.7;
			}
		}
	}
}
</style>